import React, { useState, useEffect } from 'react'
import { IUdFormItem, UdDateRangePicker, UdModalForm, UdTable, http, validators } from '@/lib'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { Icon, Input, Spin, InputNumber } from 'antd'
import udMainStore from '@/store/UdMain'
import NotFoundContent from '@/components/NotFoundContent'
import apis from '@/apis'
import dayjs from 'dayjs'
import { WrappedFormUtils } from 'antd/lib/form/Form'

let fetchTimer = null
let modalForm: WrappedFormUtils

export default function YearQuotaModalContent(props) {
  const [querying, setQuerying] = useState(false)
  const [customerCodes, setCustomerCodes] = useState<any>([])
  const [customerNames, setCustomerNames] = useState<any>([])
  const [brandList, setBrandList] = useState<any>([])
  const [assessYears, setAssessYears] = useState<any>([])
  const [materialClass, setMaterialClass] = useState<any>([])

  const getCustomerList = async (params) => {
    setQuerying(true)
    try {
      const customerRes: any = await http.get(apis.GetDealerSelectListBySearch, { params })
      const customerList = customerRes?.data?.map(item => ({ value: item?.agentCode, title: item?.agentName, agentType: item.agentType }))
      setQuerying(false)
      return customerList
    } catch (error) {
      setQuerying(false)
      return []
    }
  }

  /* 节流获取搜索的经销商 */
  const fetchCustomerHandle = (value, type) => {
    if (!value) {
      return
    }
    if (fetchTimer) {
      clearTimeout(fetchTimer)
    }
    fetchTimer = setTimeout(async () => {
      if (type == 'code') {
        setCustomerCodes([])
        const options = await getCustomerList({ agentCode: value })
        setCustomerCodes(options)
      } else if (type == 'name') {
        setCustomerNames([])
        const options = await getCustomerList({ agentName: value })
        setCustomerNames(options)
      }
      fetchTimer = null
    }, 500)
  }

  const customerChangeHandle = (val, type) => {
    const form = modalForm
    let options = []
    if (val) {
      if (type == 'code') {
        options = customerCodes.filter(item => item.value == val)
        setCustomerNames(options)
      } else {
        const code = val.key
        options = customerNames.filter(item => item.value == code).map(item => ({ agentType: item.agentType, value: item.value, title: item.value}))
        setCustomerCodes(options)
      }
    }
    setMaterialClass([])
    let dealerType = options[0] && options[0].agentType
    dealerType = dealerType == 0 ? '经销商' : '分销商'
    if (type == 'code') {
      const nameValue = { key: val, label: options[0].title }
      form.setFieldsValue({ dealerName: nameValue, brandCode: undefined, dealerType, year: undefined, 'startTime|endTime': undefined })
    } else {
      const codeValue = val.key
      form.setFieldsValue({ dealerCode: codeValue, brandCode: undefined, dealerType, year: undefined, 'startTime|endTime': undefined })
    }
    const code = type == 'code' ? val : val?.key
    if (code) {
      getBrandByDealerCode(code)
    } else {
      setBrandList([])
    }
  }

  const customerNameChange = (val) => {
    const form = modalForm
    if (val) {
      const options = [{ value: val.key, title: val.label}]
      setCustomerCodes(options)
    }
    setMaterialClass([])
    form.setFieldsValue({ dealerCode: val, brandCode: undefined, dealerType: undefined, year: undefined, 'startTime|endTime': undefined })
    const code = val?.key
    if (code) {
      getBrandByDealerCode(code)
    } else {
      setBrandList([])
    }
  }

  /* 品牌改变获取考核年和物料分类数据 */
  const brandChangeHandle = (val) => {
    modalForm.setFieldsValue({ year: undefined, 'startTime|endTime': undefined })
    if (val && val.key) {
      let brandCode = val.key
      let dealerCode = modalForm.getFieldValue('dealerCode')
      // http.post(apis.GetAssessYearByBrand, { brandCode: code }).then(res => {
      //   const years = res.data?.map(item => ({ ...item, value: item.year, title: item.name})) || []
      //   setAssessYears(years)
      // })
      const getAssessYears = http.post(apis.GetAssessYearByBrand, { brandCode })
      const getMaterialClass = http.get(apis.GetMaterialClassByDealerAndBrand, { params : { brandCode, dealerCode }})
      Promise.all([getAssessYears, getMaterialClass]).then(result => {
        const assessYearsRes = result[0]
        const materialClassRes = result[1]
        const years = assessYearsRes.data?.map(item => ({ ...item, value: item.year, title: item.name})) || []
        setAssessYears(years)
        // 通过品牌和经销商获取的物料分类数据
        const materialClass = materialClassRes?.data?.map(({code: productGroupCode, name: productGroupName }) => ({ productGroupCode, productGroupName }))
        setMaterialClass(materialClass)
      })
    } else {
      setAssessYears([])
      setMaterialClass([])
    }
  }

  /* 考核年变化获取对应的考核时间范围 */
  const yearChangeHandle = (year) => {
    const yearInfo = assessYears.find(item => item.value == year) || {}
    const { startTime, endTime } = yearInfo
    const rangTime = [startTime, endTime]
    modalForm.setFieldsValue({'startTime|endTime': rangTime})
  }
  
  /* 通过经销商获取品牌 */
  const getBrandByDealerCode = (code) => {
    http.get(apis.BrandCompanyByDealerCode, { params: { agentCode: code } }).then(res => {
      const brandList = res?.data?.map(({brandCode: value, brandName: title}) => ({ value, title })) || []
      setBrandList(brandList)
    })
  }

  /* 物料分类数据变更 */
  const changeMaterialData = (rowData) => {
    const newData = [ ...materialClass ]
    const index = newData.findIndex(data => data.productGroupCode == rowData.productGroupCode)
    newData.splice(index, 1, rowData)
    setMaterialClass(newData)
  }

  const items: IUdFormItem[] = [
    { label: '客户编码', id: 'dealerCode', rules: [validators.required], render: () => {
      return (
        <UdSelect
          optionFilterProp="children"
          // labelInValue={true}
          showSearch={true}
          // optionLabelProp= 'value'
          notFoundContent={querying ? <Spin size="small" /> : <NotFoundContent />}
          onSearch={(val) => fetchCustomerHandle(val, 'code')}
          onChange={(val, option) => customerChangeHandle(val, 'code')}
          // onPopupScroll={customerSelectScroll}
          placeholder='请输入客户编码搜索'
          suffixIcon={<Icon type='search' />}
          className='ud-search-select'
          options={customerCodes}
          mapping={{value: 'value', title: 'value'}}
        />
      )
    } },
    { label: '客户名称', id: 'dealerName', rules: [validators.required], render: () => {
      return (
        <UdSelect
          optionFilterProp="children"
          labelInValue={true}
          showSearch={true}
          notFoundContent={querying ? <Spin size="small" /> : <NotFoundContent />}
          onSearch={(val) => fetchCustomerHandle(val, 'name')}
          onChange={(val) => customerChangeHandle(val, 'name')}
          // onPopupScroll={customerSelectScroll}
          placeholder='请输入客户名称搜索'
          suffixIcon={<Icon type='search' />}
          className='ud-search-select'
          options={customerNames}
        />
      )
    } },
    { label: '品牌公司', id: 'brandCode', rules: [validators.required], render: () => <UdSelect labelInValue onChange={brandChangeHandle} options={brandList} /> },
    { label: '客户类型', id: 'dealerType', render: <Input disabled /> },
    { label: '考核年度', id: 'year', rules: [validators.required], render: () => <UdSelect onChange={yearChangeHandle} options={assessYears} /> },
    { label: '起止时间', id: ['startTime', 'endTime'], render: () => {
      return <UdDateRangePicker disabled />
    } },
    {
      label: '', id: 'saveQuotaYearLimitMaterialClassifyList', className: 'material-class-table', wrapperCol: { span: 24 }, render: () => {
        return <MaterialClassTable dataSource={materialClass} changeMaterialData={changeMaterialData} />
      }
    },
  ]
  return (
    <UdModalForm {...props} getForm={(form) => modalForm = form} items={items} />
  )
}

function MaterialClassTable(props) {

  const { dataSource, onChange, changeMaterialData } = props

  useEffect(() => {
    // 父组件传入的dataSource更新，在此触发将最新数据传给表单
    dataSource && onChange(dataSource)
  }, [dataSource])

  const quotaChange = (key, value, row) => {
    // const newData = [ ...props.dataSource ]
    // const index = newData.findIndex(data => data.code == row.code)
    // newData.splice(index, 1, { ...row, [key]: value})
    // onChange && onChange(newData)
    row[key] = value
    // 提交给父组件更新，避免每次更新旧的props.daataSource数据，得不到正确数据
    changeMaterialData && changeMaterialData(row)
  }

  const columns = [
    { title: '序号', dataIndex: 'no', render: (text, record, index) => index + 1 },
    { title: '物料分类编号', dataIndex: 'productGroupCode' },
    { title: '物料分类名称', dataIndex: 'productGroupName' },
    { title: '全年总配额数量(件)', dataIndex: 'number', render: (text, record) => {
      return <InputNumber defaultValue={text} onBlur={(e) => quotaChange('number', e.target.value, record)} min={0} max={2**31} maxLength={9} precision={0} style={{width: 110}} />
    } },
  ]
  return (
    <UdTable
      columns={columns}
      pagination={false}
      dataSource={dataSource}
    />
  )
}

export function EditYearQuotaModalContent(props) {
  const { values } = props
  const [materialClass, setMaterialClass] = useState([])

  useEffect(() => {
    const { productGroupCode, productGroupName, number } = values
    setMaterialClass([{ productGroupCode, productGroupName, number }])
  }, [])

  /* 物料分类数据变更 */
  const changeMaterialData = (rowData) => {
    const newData = [ ...materialClass ]
    const index = newData.findIndex(data => data.code == rowData.code)
    newData.splice(index, 1, rowData)
    setMaterialClass(newData)
  }

  const items: IUdFormItem[] = [
    { label: '客户编码', id: 'dealerCode', render: <div>{values.dealerCode}</div> },
    { label: '客户名称', id: 'dealerName', render: <div>{values.dealerName}</div> },
    { label: '品牌公司', id: 'brandName', render: <div>{values.brandName}</div> },
    { label: '客户类型', id: 'dealerType', render: <div>{values.dealerType}</div> },
    { label: '考核年度', id: 'year', render: <div>{values.year}</div> },
    { label: '起止时间', id: ['startTime', 'endTime'], render: () => {
      let render = values.startTime ? dayjs(values.startTime).format('YYYY-MM-DD') : ''
      render += values.endTime ? '~' + dayjs(values.endTime).format('YYYY-MM-DD') : ''
      return <div>{render}</div>
    } },
    {
      label: '', id: 'saveQuotaYearLimitMaterialClassifyList', className: 'material-class-table', wrapperCol: { span: 24 }, render: () => {
        return <MaterialClassTable dataSource={materialClass} changeMaterialData={changeMaterialData} />
      }
    },
  ]
  return (
    <UdModalForm {...props} items={items} values={values} />
  )
}
